package com.deductive.web.disposition.assumed;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.deductive.common.config.RuoYiConfig;
import com.deductive.common.core.controller.BaseController;
import com.deductive.common.core.domain.AjaxResult;
import com.deductive.common.core.page.TableDataInfo;
import com.deductive.domain.assumed.AssumedEnemyInfo;
import com.deductive.domain.sys.SysFiles;
import com.deductive.service.assumed.EnemyInfoService;
import com.deductive.service.sys.SysFilesService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/enemyInfo")
@Api(tags = "想定-敌情管理")
public class AssumedEnemyInfoController extends BaseController {

    @Resource
    private EnemyInfoService enemyInfoService;

    @Resource
    private SysFilesService sysFilesService;

    @GetMapping("/queryPage")
    @ApiOperation("敌情分页查询")
    public TableDataInfo queryPage(@ApiParam("按想定ID过滤") AssumedEnemyInfo q) {
        startPage();
        LambdaQueryWrapper<AssumedEnemyInfo> w = new LambdaQueryWrapper<>();
        Long assumedId = q.getAssumedId();
        w.eq(assumedId != null && assumedId > 0, AssumedEnemyInfo::getAssumedId, assumedId);
        w.orderByDesc(AssumedEnemyInfo::getCreateTime);
        List<AssumedEnemyInfo> list = enemyInfoService.list(w);
        return getDataTable(list);
    }

    @GetMapping("/queryList")
    @ApiOperation("敌情列表查询")
    public AjaxResult queryList(@ApiParam("按想定ID过滤") AssumedEnemyInfo q) {
        LambdaQueryWrapper<AssumedEnemyInfo> w = new LambdaQueryWrapper<>();
        Long assumedId = q.getAssumedId();
        w.eq(assumedId != null && assumedId > 0, AssumedEnemyInfo::getAssumedId, assumedId);
        w.orderByDesc(AssumedEnemyInfo::getCreateTime);
        return success(enemyInfoService.list(w));
    }

    @PostMapping("/insert")
    @ApiOperation("新增敌情")
    public boolean insert(@ApiParam("敌情对象") @RequestBody AssumedEnemyInfo e) {
        e.setCreateTime(new Date());
        return enemyInfoService.save(e);
    }

    @PostMapping("/update")
    @ApiOperation("修改敌情")
    public boolean update(@ApiParam("敌情对象") @RequestBody AssumedEnemyInfo e) {
        e.setUpdateTime(new Date());
        return enemyInfoService.updateById(e);
    }

    @DeleteMapping
    @ApiOperation("删除敌情并删除关联文件")
    public AjaxResult delete(@ApiParam(value = "敌情ID列表", required = true, example = "[1,2]") @RequestParam("idList") List<Long> idList) {
        List<AssumedEnemyInfo> infos = enemyInfoService.listByIds(idList);
        for (AssumedEnemyInfo info : infos) {
            if (info != null && StringUtils.isNotBlank(info.getFileIds())) {
                List<Long> fileIds = Arrays.stream(info.getFileIds().split(","))
                        .filter(StringUtils::isNotBlank)
                        .map(Long::valueOf)
                        .collect(Collectors.toList());
                if (!fileIds.isEmpty()) {
                    List<SysFiles> files = sysFilesService.listByIds(fileIds);
                    deletePhysicalFiles(files);
                    sysFilesService.removeByIds(fileIds);
                }
            }
        }
        return success(enemyInfoService.removeByIds(idList));
    }

    private void deletePhysicalFiles(List<SysFiles> files) {
        for (SysFiles file : files) {
            try {
                String physicalPath = file.getFilePath().replace("/profile/", RuoYiConfig.getProfile() + "/");
                Path filePath = Paths.get(physicalPath);
                if (Files.exists(filePath)) {
                    Files.delete(filePath);
                    deleteEmptyDirectories(filePath.getParent());
                }
            } catch (IOException ignored) { }
        }
    }

    private void deleteEmptyDirectories(Path directory) {
        try {
            if (directory != null && Files.exists(directory)) {
                if (Files.list(directory).count() == 0) {
                    Files.delete(directory);
                    deleteEmptyDirectories(directory.getParent());
                }
            }
        } catch (IOException ignored) { }
    }
}


